package 剑指offer.第11天_双指针;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 * 剑指 Offer 18. 删除链表的节点
 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。
 返回删除后的链表的头节点。
 注意：此题对比原题有改动
 示例 1:
 输入: head = [4,5,1,9], val = 5
 输出: [4,1,9]
 解释: 给定你链表中值为 5 的第二个节点，那么在调用了你的函数之后，该链表应变为 4 -> 1 -> 9.
 */
class Solution {
    public ListNode deleteNode1(ListNode head, int val) {
        ListNode tmp0 = head;
        ListNode tmp1 = head;
        if (tmp1.val == val) {
            return tmp1.next;
        }else{
            tmp1 = head.next;
        }
        return null;

    }
    public ListNode deleteNode2(ListNode head, int val) {
        if(head == null) return head;
        ListNode cur = head;
        ListNode pre = null;
        if(cur.val == val) return head.next;
        while(cur.val != val) {
            pre = cur;// 修改节点指向，往后移一个节点
            cur = cur.next;
        }
//        pre.next = pre.next.next;// 已定位节点cur,跳出循环，修改节点指向，即pre.next=cur.next
        pre.next = cur.next;
        return head;
    }
    public ListNode deleteNode(ListNode head, int val) {
        if(head.val == val) return head.next;
        ListNode pre = head, cur = head.next;
        while(cur != null && cur.val != val) {
            pre = cur;
            cur = cur.next;
        }
        if(cur != null) pre.next = cur.next;
        return head;
    }


    public static void main(String[] args) {
//        4,5,1,9
        ListNode listNode = new ListNode(4);
        listNode.next = new ListNode(5);
        listNode.next.next = new ListNode(1);
        listNode.next.next.next = new ListNode(0);
        ListNode node = new Solution().deleteNode2(listNode, 1);
        System.out.println("listNode = " + node);

    }
}
